package controller;

import dao.customerDao.CustomerDaoImpl;
import model.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/insertCustomer")
public class InsertServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CustomerDaoImpl dao = new CustomerDaoImpl();
        String message;

        try {
            String name = new String(request.getParameter("name").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String email = new String(request.getParameter("email").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            double balance = Double.parseDouble(request.getParameter("balance"));
            Customer customer = new Customer(name, email, balance);
            boolean success = dao.addCustomer(customer);
            if (success) {
                message = "成功插入一条信息";
            } else {
                message = "插入记录错误!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "插入记录失败!";
        }
        request.setAttribute("result", message);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
